const { create ,findAddress,update,remove} = require("../server/address.js")

async function createAddress(ctx){
    let user_id=ctx.state.user.id
   let {consignee,phone,address}=ctx.request.body
   try{
    let res=await create({user_id,consignee,phone,address})
    ctx.body={
        code:200,
        message:"地址添加成功",
        result:{
            res
        }
    }
   }catch(error){
       console.log(error)
      return ctx.app.emit('error',{
           code:50000,
           message:"地址添加失败"+error,
           result:''
       },ctx)
   }
   
}

async function getAddress(ctx){
    let user_id=ctx.state.user.id
    try{
       let res=await findAddress(user_id)
       ctx.body={
           code:200,
           message:'获取地址成功',
           result:{
               address:res
           }
       }
    }catch(error){
      console.log(error)
      ctx.app.emit('error',{
          code:50000,
        message:"获取地址失败"+error,
        result:""
      },ctx)
    }
}

async function updateAddress(){
    try{
        let user_id=ctx.state.user.id
        let id=ctx.request.params.id
        let {phone,address,consignee}=ctx.request.body
       let res=await update({user_id,id,phone,address,consignee})
       if(res){
           ctx.body={
               code:200,
               message:"地址更新成功",
               result:{
                   res
               }
           }
       }else{
            ctx.app.emit('error',{
                code:50000,
                message:"更新地址失败",
                result:""
            },ctx)
        }
    }catch(error){
        console.log(error)
        ctx.app.emit('error',{
            code:50000,
            message:"更新地址失败",
            result:""
        },ctx)
    }
}

async function removeAddress(ctx){
   let id=ctx.request.params.id
   try{
    let res=await remove(id)
      if(res){
        ctx.body={
            code:200,
            message:'地址删除成功',
            result:''
        }
      }else{
          ctx.app.emit('error',{
              code:40000,
              message:"删除地址失败",
              result:''
          },ctx)
      }
   }catch(error){
       ctx.app.emit('error',{
           code:50000,
           message:"地址删除失败"+error,
           result:''
       },ctx)
   }
   

}
module.exports={
    createAddress,
    getAddress,
    updateAddress,
    removeAddress
}